﻿using B.S.ProductionProject.Domain;
using B.S.ProductionProject.ErrorCode;
using B.S.ProductionProject.Read.WebAPI.Applications.Commands.ProductionScheduleDetailCommand;
using MediatR;
using SqlSugar;

namespace B.S.ProductionProject.Read.WebAPI.Applications.CommandHandlers.ProductionScheduleDetailCommandHandler
{
    public class GetProductionScheduleDetailCommandHandler : IRequestHandler<GetProductionScheduleDetailCommand, APIResult<APIPaging<ProductionScheduleDetail>>>
    {
        private readonly ISqlSugarClient db;

        public GetProductionScheduleDetailCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<APIPaging<ProductionScheduleDetail>>> Handle(GetProductionScheduleDetailCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<ProductionScheduleDetail>> result = new APIResult<APIPaging<ProductionScheduleDetail>>();
            result.code = APIResultCode.success;
            result.msg = "查询显示成功";

            var list = db.Queryable<ProductionScheduleDetail>().Where(p => p.isDelete == false && p.ProductionPlanningId == request.ProductionPlanningId);

            int TotalCount = list.Count();
            int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(p => p.ProductionScheduleDetailId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPaging<ProductionScheduleDetail> paging = new APIPaging<ProductionScheduleDetail>();
            paging.TotalCount = TotalCount;
            paging.TotalPage = TotalPage;
            paging.list = list.ToList();

            result.data = paging;

            return await Task.FromResult(result);
        }
    }
}
